package com.solocredit.finance.ui.steps.fm

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.utils.ImageUtil
import com.solocredit.finance.base.utils.log.MullaLog
import com.solocredit.finance.base.utils.permission.OnPermissionCallback
import com.solocredit.finance.base.utils.permission.Permission
import com.solocredit.finance.base.utils.permission.XXPermissions
import com.solocredit.finance.databinding.FmMullaStepSelfieBinding
import com.solocredit.finance.http.ApiService
import com.solocredit.finance.http.ApiService.addCommonParams
import com.solocredit.finance.http.ApiService.addRandomParams
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.ProFm
import com.solocredit.finance.ui.steps.act.MullaCameraSelfieAct
import com.solocredit.finance.ui.steps.act.MullaStepsAct
import com.solocredit.finance.utils.dialog.PermissionReasonDialog
import com.solocredit.finance.utils.dialog.VerificationSendSuccessDialog
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaPermissionHelper
import com.solocredit.finance.utils.track.FlexiMolaTracker
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/31 13:40
 * @Annotation：认证流程 - 自拍照
 */
class MullaStepSelfieFm(): ProFm() {
    private var _binding: FmMullaStepSelfieBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var selfieCallBack: ((String) -> Unit)? = null
    private var stepItem: JSONObject? = null
    //是否选中删除信息,默认选中
    private var isSelectedDelete = true

    //本地预览地址
    private var faceImgPath = ""
    //拍摄的头像地址
    private var faceImgUrl = ""

    companion object {
        fun newInstance(stepItem: JSONObject,callBack: (String) -> Unit): MullaStepSelfieFm {
            return MullaStepSelfieFm(stepItem,callBack)
        }
    }

    constructor(stepItem: JSONObject,callBack: (String) -> Unit): this(){
        this.stepItem = stepItem
        selfieCallBack = callBack
    }

    override fun getMullaRootView(inflater: LayoutInflater): View {
        _binding = FmMullaStepSelfieBinding.inflate(inflater)
        return binding.root
    }

    override fun initMullaView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))
        if (stepItem != null){
            _binding?.textStepTitle?.text = stepItem?.optString("showTitle")
        }
        showFlexiMolaSelfieBeforeView()

        // TODO: 2025.09.10 联系人提交按钮在上层MullaStepsAct控制
        _binding?.btnNext?.visibility = View.GONE
    }

    override fun initMullaListener() {
        _binding?.selifeDeleteTipsLayout?.setOnClickListener {
            isSelectedDelete = !isSelectedDelete
            showFlexiMolaSelfieDeleteInformationTips()
        }
        _binding?.viewMask?.setOnClickListener {
            if (XXPermissions.isGranted(requireContext(), Permission.CAMERA)){
                openFlexiMolaSelfieCamera()
            } else {
                val item = MullaPermissionHelper.takeMullaPerCameraItem()
                showFlexiMolaPermissionReasonDialog(item)
            }
        }
        _binding?.imgRetake?.setOnClickListener {
            _binding?.viewMask?.callOnClick()
        }
        _binding?.imgView?.setOnClickListener {
            _binding?.viewMask?.callOnClick()
        }
        //提交
        _binding?.btnNext?.setOnClickListener {
            onFlexiMolaSubmitSelfieAction()
        }
    }

    override fun initMullaData() {
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_STEP_SELFIE_START)

        val showApprovedKey1 = getString(R.string.step_selfie_upload_credit_limit_approved_tips_key1)
        val showApprovedKey2 = getString(R.string.step_selfie_upload_credit_limit_approved_tips_key2)
        val showApprovedText = String.format(getString(R.string.step_selfie_upload_credit_limit_approved_tips),showApprovedKey1,showApprovedKey2)
        val startApprovedIndex1 = showApprovedText.indexOf(showApprovedKey1)
        val startApprovedIndex2 = showApprovedText.indexOf(showApprovedKey2)
        val approvedTipsSpannable = SpannableString(showApprovedText)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(Color.parseColor("#FF00CB48")), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(Color.parseColor("#FF00CB48")), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textStepSelfieLimitApprovedTips.text = approvedTipsSpannable
    }

    /**
     * 人脸拍照
     */
    private val faceCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                val faceImgPath = result.data?.getStringExtra("imgLocalPath").toString()
                MullaLog.e(">>>>>>>>>face info ：$faceImgPath")
                val imgLocalPath = result.data?.getStringExtra("imgLocalPath").toString()
                val imgUrl = result.data?.getStringExtra("imgUrl").toString()
                showFlexiMolaSelfieAfterView(imgLocalPath,imgUrl)
            }
        }
    }

    /**
     * 显示未拍照View
     */
    private fun showFlexiMolaSelfieBeforeView(){
        _binding?.let { binding ->
            binding.imgView.setImageResource(R.mipmap.mulla_step_selfie_default_avater)
            binding.imgView.borderColor = Color.parseColor("#FF160807")
            binding.viewMask.visibility = View.GONE
            binding.imgRetake.visibility = View.GONE
            binding.textRetake.visibility = View.GONE
            binding.textClickTake.visibility = View.VISIBLE
            binding.btnNext.text = getString(R.string.step_selfie_take)
            selfieCallBack?.invoke(faceImgUrl)
        }
    }

    /**
     * 显示拍照之后的View
     */
    private fun showFlexiMolaSelfieAfterView(imgPath: String, imgUrl: String){
        faceImgPath = imgPath
        faceImgUrl = imgUrl
        _binding?.let { binding ->
            ImageUtil.instance?.loadImageUrl(requireContext(),binding.imgView,faceImgPath)
            binding.imgView.borderColor = Color.parseColor("#FFD21034")
            binding.viewMask.visibility = View.VISIBLE
            binding.imgRetake.visibility = View.VISIBLE
            binding.textRetake.visibility = View.VISIBLE
            binding.textClickTake.visibility = View.GONE
            binding.btnNext.text = getString(R.string.step_selfie_submit)

            selfieCallBack?.invoke(faceImgUrl)
        }
    }

    private fun showFlexiMolaSelfieDeleteInformationTips(){
        when(isSelectedDelete){
            true -> {
                _binding?.imgSelifeDeleteTipsSelect?.setImageResource(R.mipmap.mulla_coupon_selected)
            }
            else -> {
                _binding?.imgSelifeDeleteTipsSelect?.setImageResource(R.mipmap.mulla_coupon_normal)
            }
        }
    }

    /**
     * 打开相机
     */
    private fun openFlexiMolaSelfieCamera(){
        HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_STEP_SELFIE_START_TAKE,"")
        faceCameraResultLauncher.launch(Intent(context, MullaCameraSelfieAct::class.java))
    }

    /**
     * 权限说明dialog
     */
    private fun showFlexiMolaPermissionReasonDialog(data: JSONObject) {
        val reasonDialog = PermissionReasonDialog(context,"Selfie Page",object: PermissionReasonDialog.IDialogCallback{
            override fun onDenyClick() {
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_DENY,data.optString("permission"))
            }
            override fun onAgreeClick() {
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_AGREE,data.optString("permission"))
                requestFlexiMolaPermission(data)
            }
        })
        reasonDialog.setCancelable(true)
        reasonDialog.setCanceledOnTouchOutside(true)
        reasonDialog.show()
        reasonDialog.showFlexiMolaPermission(data)
    }

    /**
     * 授权
     */
    private fun requestFlexiMolaPermission(data: JSONObject){
        val permission = data.optString("permission")
        XXPermissions.with(requireContext())
            // 申请多个权限
            .permission(permission)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        openFlexiMolaSelfieCamera()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))

                    XXPermissions.startPermissionActivity(requireContext(),permission)
                }
            })
    }

    private fun showMullaDeleteInfoDialog(params: JSONObject){
        val sendSuccessDialog = VerificationSendSuccessDialog(requireContext())
        sendSuccessDialog.setCancelable(true)
        sendSuccessDialog.setCanceledOnTouchOutside(false)
        sendSuccessDialog.show()
        sendSuccessDialog.showMullaSuccessTips(getString(R.string.step_selfie_delete_submit_success_tips))
        launch(Dispatchers.Main){
            delay(1500)
            if (isAdded && !requireActivity().isFinishing && sendSuccessDialog.isShowing) {
                sendSuccessDialog.dismiss()
            }

            val act = context as MullaStepsAct
            act.onMullaSubmitProcessAction(ApiService.API_PATH.MULLA_API_OCR_INFO_PATH,params)
        }
    }

    /**
     * 提交或开始人脸拍照
     */
    private fun onFlexiMolaSubmitSelfieAction(){
        //开始人脸拍照
        if (faceImgUrl.isEmpty()){
            _binding?.viewMask?.callOnClick()
            return
        }
        HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_STEP_SELFIE_CONFIRM_SUBMIT)
        // TODO: Step Next 批量埋点上报
        FlexiMolaTracker.getInstance(MyApp.app).reportImmediately(null)
        //提交
        val params = JSONObject().addCommonParams().addRandomParams().apply {
//                put("path", ApiService.API_PATH.MULLA_API_OCR_INFO_PATH)
            put("cardType","FACE")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
            put("faceImgUrl",faceImgUrl)//人脸图片
        }
        if (isSelectedDelete){
            showMullaDeleteInfoDialog(params)
        } else {
            val act = context as MullaStepsAct
            act.onMullaSubmitProcessAction(ApiService.API_PATH.MULLA_API_OCR_INFO_PATH,params)
        }
    }

    override fun onMullaEvent(event: MullaEventData) {
        super.onMullaEvent(event)
        if(event.eventType == MullaEventData.TYPE.MULLA_STEP_DATA_SUBMIT){//提交信息
            onFlexiMolaSubmitSelfieAction()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_STEP_SELFIE_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}